package git.bankview.wl.report;

import java.util.*;
import java.text.*;
import java.sql.*;

import laya.semi.process.*;

import git.bankview.sl.db.*;
import git.bankview.wl.bean.LogonBean;
import git.bankview.sl.report.ReportCommon;

import org.apache.log4j.Logger;

public class ReportTransAuthLoader
	implements IGenericClassActivity
{
	private static Logger log = Logger.getLogger(ReportTransAuthLoader.class);

	private static String SQL_USERAUTHSELECTOR = 
		"SELECT ur.userid roleid, ur.username rolelabel, rt.methodid, rt.statuscode"
		+ " FROM infouser ur, roletrans rt"
		+ " WHERE rt.transid = ? and ur.userid = rt.roleid"
		+ " ORDER BY ur.userid, rt.methodid";
	
	private static String SQL_ROLEAUTHSELECTOR = 
		"SELECT ir.roleid, ir.rolelabel, rt.methodid, rt.statuscode"
		+ " FROM inforole ir, roletrans rt"
		+ " WHERE rt.transid = ? and ir.roleid = rt.roleid"
		+ " ORDER BY ir.roleid, rt.methodid";
	
	public void execute(IProcessContext oCtx)
		throws Exception
	{
		String oTransid = (String)oCtx.getField("transid");
		
		Connection oConn = DBConnectionFactory.getCoreConnection();
		try
		{
			fillArrayFields(oCtx, oTransid, new String[] {"roleids", "rolelabels", "rolemethodids", "rolestatuscodes"}, SQL_ROLEAUTHSELECTOR, oConn);
			fillArrayFields(oCtx, oTransid, new String[] {"userids", "usernames", "usermethodids", "userstatuscodes"}, SQL_USERAUTHSELECTOR, oConn);
		}
		finally
		{
			oConn.close();
		}
	}
	
	private int fillArrayFields(IProcessContext oCtx, String transId, String[] vFieldName, String sql, Connection oConn)
		throws Exception
	{
		log.debug(sql);
		PreparedStatement ps = oConn.prepareStatement(sql);
		ps.setString(1, transId);
		Vector v = new Vector();
		int nRows = DBUtil.resultSetToList(v, ps.executeQuery(), 0, 0);
		String[] vId = new String[nRows];
		String[] vLabel = new String[nRows];
		Integer[] vMethod = new Integer[nRows];
		Integer[] vCode = new Integer[nRows];
		
		for (int i = 0; i < nRows; ++i)
		{
			Map r = (Map)v.get(i);
			vId[i] = ((String)r.get("roleid")).trim();
			vLabel[i] = ((String)r.get("rolelabel")).trim();
			vMethod[i] = Integer.valueOf(r.get("methodid").toString());
			vCode[i] = Integer.valueOf(r.get("statuscode").toString());
		}
		
		oCtx.setField(vFieldName[0], vId);
		oCtx.setField(vFieldName[1], vLabel);
		oCtx.setField(vFieldName[2], vMethod);
		oCtx.setField(vFieldName[3], vCode);
		
		return nRows;
	}
}
